package com.taocore.invite;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter, Constants{

	static Logger _log = Logger.getLogger(SessionFilter.class.getName());

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	
	private boolean verify(ServletRequest req) throws IOException, ServletException
	{
		//req.setCharacterEncoding("GBK");
		String queryString = ((HttpServletRequest)req).getQueryString();
		_log.info(queryString);
		HttpSession session = ((HttpServletRequest)req).getSession(false);
		if (session != null && session.getAttribute(USER) != null)
		{
			return true;
		}
		return false;
	}
	
	public void doFilter(ServletRequest req, ServletResponse rsp,
			FilterChain chain) throws IOException, ServletException {
		try 
		{
			if (verify(req))
		    {
		    	chain.doFilter(req, rsp);
		    }
			else
			{
				((HttpServletResponse)rsp).sendRedirect("login");
			}
		} 
		catch (IOException e) {
			_log.log(Level.SEVERE, "", e);
			throw e;
		}
	}
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
